package com.machine.filling.net.serialPort.util;

import android.util.Log;

import com.machine.filling.Test.TestCommon;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import android_serialport_api.SerialPort;

/**
 * Created by sperfan on 2018/3/20.
 *
 * @描述:
 */

public class SerialPortToolManager {

    private static final String TAG = "SerialPortToolManager";
    private Map<String, SerialPortTool> pool;

    private static SerialPortToolManager instance;

    public SerialPortToolManager() {
        pool = new HashMap<>();
    }

    public static SerialPortToolManager getInstance() {
        if (instance == null) {
            synchronized (SerialPortToolManager.class) {
                if (instance == null) {
                    instance = new SerialPortToolManager();
                }
            }
        }

        return instance;
    }

    /**
     * 打开某个串口
     *  一个串口号 对应一个串口工具类
     * @param serialNum
     */
    public void openSerialPort(String serialNum, SerialPortTool.OnSerialPortDataReceiveListener listener) {
        if (getSerialPortTool(serialNum) != null) {
            Log.d(TAG, "openSerialPort() returned:[" + serialNum + "]该串口已经开启...");
            return;
        }else {
            Log.d(TAG, "openSerialPort() returned: " + "尝试打开串口" + serialNum);
        }
        SerialPortTool serialPortTool = new SerialPortTool(serialNum);
        if (TestCommon.isTest_SerialPort) {
            serialPortTool.setOnSerialPortDataReceiveListener(listener);
            serialPortTool.testSimulateSerialPort();
            pool.put(serialNum, serialPortTool);
        } else {
            SerialPort serialPort = serialPortTool.openSerialPort();
            if (serialPort != null) {
                serialPortTool.setOnSerialPortDataReceiveListener(listener);
                pool.put(serialNum, serialPortTool);
            }else{
                Log.d(TAG, "openSerialPort() returned: [" + serialNum + "]串口开启失败");
            }
        }
    }


    public SerialPortTool getSerialPortTool(String serialNum) {
        return pool.get(serialNum);
    }

    /**
     * 向某个串口发命令
     *
     * @param serialNum
     * @param hexStr
     */
    public void sendSerialPortCMD_DATA(String serialNum, String hexStr) {
        SerialPortTool serialPortTool = getSerialPortTool(serialNum);
        serialPortTool.sendSerialPort(hexStr);
    }

    /**
     * 关闭某个串口
     *
     * @param serialNum
     */
    public void closeSerialPort(String serialNum) {
        SerialPortTool serialPortTool = getSerialPortTool(serialNum);
        serialPortTool.closeSerialPort();
    }

    public void closeAll(){
        for (String key : pool.keySet()) {
            pool.get(key).closeSerialPort();
        }
        pool = new HashMap<>();
    }
}
